package com.xtravel.discovery.activity;

import android.content.Context;
import android.os.AsyncTask;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AbsListView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.handmark.pulltorefresh.library.ILoadingLayout;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.lidroid.xutils.BitmapUtils;
import com.lidroid.xutils.bitmap.PauseOnScrollListener;

import java.util.ArrayList;
import java.util.List;

import com.xtravel.R;
import com.xtravel.common.adapter.BaseDataAdapter;
import com.xtravel.common.database.dto.DtoBase;
import com.xtravel.discovery.adapter.LiveRecordsAdapter;
import com.xtravel.discovery.adapter.StateLiveRecordsAdapter;
import com.xtravel.discovery.api.LiveRequest;
import com.xtravel.discovery.dto.CountryState;
import com.xtravel.discovery.dto.LiveRecord;
import com.xtravel.discovery.dto.StateLiveRecord;

/**
 * Created by Memory on 15/11/4.
 */
public class LiveRecordsView extends LinearLayout {
    private CountryState countryState;
    private BaseDataAdapter recordsAdapter;
    private PullToRefreshListView recordsList;
    private ListView itemsListView;
    private Context context;
    private BitmapUtils bitmapUtils;
    private boolean isLatest;
    /**
     * 是否正在加载数据，如果正在加载，则不进行加载，如果没有，则加载，
     * 用于用户数滑动列表
     */
    private Boolean isRefreshing = false;
    private View footerView;
    private TextView tvFooterText;
    private LiveRequest apiRequest = new LiveRequest();

    public LiveRecordsView(Context context, CountryState region, BitmapUtils bitmapUtils) {
        super(context);
        this.context = context;
        this.bitmapUtils = bitmapUtils;
        this.countryState = region;
        LayoutInflater inflater = LayoutInflater.from(context);
        View view = inflater.inflate(R.layout.live_records_items, null);
        view.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
        recordsList = (PullToRefreshListView) view.findViewById(R.id.records_list);
        this.addView(view);
        footerView = View.inflate(context, R.layout.footer_tweet, null);
        initListView();
    }

    private void initListView() {
        this.footerView.setVisibility(View.GONE);
        this.tvFooterText = (TextView) footerView.findViewById(R.id.tvFooterText);
        this.itemsListView = recordsList.getRefreshableView();
        this.itemsListView.addFooterView(footerView);
        this.itemsListView.setBackgroundResource(R.drawable.no_data_loading);
        ILoadingLayout startLabels = recordsList.getLoadingLayoutProxy(true, false);
        startLabels.setPullLabel("正在刷新...");
        startLabels.setRefreshingLabel("正在刷新...");
        startLabels.setReleaseLabel("正在刷新...");
        ILoadingLayout endLabels = recordsList.getLoadingLayoutProxy(false, false);
        endLabels.setPullLabel("正在刷新...");
        endLabels.setRefreshingLabel("正在刷新...");
        endLabels.setReleaseLabel("正在刷新...");
        recordsList.setMode(PullToRefreshBase.Mode.PULL_FROM_START);
        recordsList.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
                // 下拉的时获取最新的数据
                getData(true);
            }

            // Pulling Up
            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
                // 上拉获取旧数据
                getData(false);
            }
        });

        recordsAdapter = getDataAdapter();
        recordsList.setAdapter(recordsAdapter);
        recordsList.setOnScrollListener(new PauseOnScrollListener(bitmapUtils, true, true, new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {
            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
                if (firstVisibleItem + visibleItemCount + 3 > totalItemCount && firstVisibleItem > 0) {
                    getData(false);
                }
            }
        }));

        this.getData(true);
    }

    private BaseDataAdapter getDataAdapter() {
        if (this.countryState.stateCode == "all") {
            return new LiveRecordsAdapter(this.context, new ArrayList<LiveRecord>(), bitmapUtils);
        } else
            return new StateLiveRecordsAdapter(this.context, new ArrayList<StateLiveRecord>(), bitmapUtils);
    }

    public void getData(boolean latest) {
        this.isLatest = latest;
        if (!this.isLatest) {
            if (isRefreshing) {
                return;
            }
            isRefreshing = true;
        }

        if (this.isLatest) {
            if (recordsAdapter.getCount() > 0) {
                this.itemsListView.setBackgroundResource(R.color.transparant);
            }

            recordsAdapter.notifyDataSetChanged();
        }

        Long sinceId = 0L, maxId = 0L;
        if (this.isLatest) {
            sinceId = recordsAdapter.getMaxId();
        } else {
            maxId = recordsAdapter.getMinId();
        }

        if (countryState.stateCode == "all") {
            new AsyncTask<Long, Void, List<LiveRecord>>() {
                @Override
                protected List<LiveRecord> doInBackground(Long... params) {
                    List<LiveRecord> records = apiRequest.getAllLiveRecords(params[0], params[1], 20);
                    return records;
                }

                @Override
                protected void onPostExecute(List<LiveRecord> records) {
                    super.onPostExecute(records);
                    Message msg = new Message();
                    msg.obj = records;
                    handler.sendMessage(msg);
                }
            }.execute(sinceId, maxId);
        } else {
            new AsyncTask<Long, Void, List<StateLiveRecord>>() {
                @Override
                protected List<StateLiveRecord> doInBackground(Long... params) {
                    List<StateLiveRecord> records = apiRequest.getStateLiveRecords(params[0], params[1], 20, countryState.stateCode);
                    return records;
                }

                @Override
                protected void onPostExecute(List<StateLiveRecord> records) {
                    super.onPostExecute(records);
                    Message msg = new Message();
                    msg.obj = records;
                    handler.sendMessage(msg);
                }
            }.execute(sinceId, maxId);
        }
    }

    public void refresh() {
        this.itemsListView.setSelection(0);
        recordsList.setRefreshing(false);
    }

    private android.os.Handler handler = new android.os.Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            recordsList.onRefreshComplete();
            List<DtoBase> records = (List<DtoBase>) msg.obj;
            List<DtoBase> newItems = new ArrayList<DtoBase>();
            for (DtoBase item : records) {
                boolean exist = recordsAdapter.isExist(item);
                if (!exist)
                    newItems.add(item);
            }

            if(newItems.size() > 0) {
                if (isLatest)
                    recordsAdapter.addRangeAtBegin(newItems);
                else
                    recordsAdapter.addRangeAtEnd(newItems);

                recordsAdapter.notifyDataSetChanged();
            }

            if (!isLatest) {
                isRefreshing = false;
            }

            if (recordsAdapter.getCount() == 0) {
                itemsListView.setBackgroundResource(R.drawable.no_data);
                return;
            } else {
                itemsListView.setBackgroundResource(R.color.transparant);
            }

            if (newItems != null && newItems.size() == 0 && !isLatest) {
                footerView.setVisibility(View.VISIBLE);
                tvFooterText.setText(R.string.str_no_data);
            }
        }
    };
}
